package com.example.demo.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.QueryPageParam;
import com.example.demo.common.Result;
import com.example.demo.entity.Knowledge;
import com.example.demo.service.IKnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-02-24
 */
@RestController
@RequestMapping("/knowledge")
public class KnowledgeController {

    @Autowired
    private IKnowledgeService knowledgeService;

    //新增
    @PostMapping("/save")
    public Result save(@RequestParam("types") String types,
                       @RequestParam("title") String title,
                       @RequestParam("content") String content,
                       @RequestParam("publisherNo") String publisherNo,
                       @RequestParam(value = "imageFile", required = false) MultipartFile imageFile){

        if (StringUtils.isBlank(title) || title.length() < 2) {
            return Result.fail("标题至少需要2个字符");
        }

        if (StringUtils.isBlank(content) || content.length() < 10) {
            return Result.fail("内容至少需要10个字符");
        }

        List<String> validTypes = Arrays.asList("小技巧", "小知识", "小趣事","新手养宠","饮食与营养","健康与医疗");
        String[] typeArr = types.split(",");
        for (String type : typeArr) {
            if (!validTypes.contains(type)) {
                return Result.fail("包含无效的分类类型: " + type);
            }
        }

        Knowledge knowledge = new Knowledge();
        knowledge.setType(types);
        knowledge.setTitle(title);
        knowledge.setContent(content);
        knowledge.setPublisherNo(publisherNo);

        try {
            if (StringUtils.isBlank(publisherNo)) {
                return Result.fail("用户未登录");
            }
            if (imageFile != null && !imageFile.isEmpty()) {
                // 校验文件大小
                if (imageFile.getSize() > 2 * 1024 * 1024) {
                    return Result.fail();
                }
                //图片类型校验
                String contentType = imageFile.getContentType();
                if (!Arrays.asList("image/jpeg", "image/png").contains(contentType)) {
                    return Result.fail("仅支持JPEG/PNG格式");
                }
                knowledge.setImageBytes(imageFile.getBytes());
                knowledge.setImageType(contentType);
            }
            boolean saveResult = knowledgeService.save(knowledge);
            return saveResult ? Result.suc() : Result.fail("数据库保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统异常: " + e.getMessage());
        }

    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam Long id){
        return knowledgeService.removeById(id)?Result.suc():Result.fail();
    }

    //图片获取接口
    @GetMapping("/image/{id}")
    public void getImage(@PathVariable Long id, HttpServletResponse response)throws IOException {
        Knowledge knowledge = knowledgeService.getById(id);
        if (knowledge == null || knowledge.getImageBytes() == null) {
            response.sendError(404, "Image not found");
            return;
        }
        String contentType = knowledge.getImageType();
        response.setContentType(contentType != null ? contentType : "image/jpeg");
        response.getOutputStream().write(knowledge.getImageBytes());

    }

    //图片上传接口
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile file,
                               @RequestParam String knowledgeId)
            throws IOException{
        if (file.isEmpty()) {
            return Result.fail();
        }
        if (!Arrays.asList("image/jpeg", "image/png").contains(file.getContentType())) {
            return Result.fail();
        }
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.fail();
        }
        Knowledge knowledge = knowledgeService.getById(knowledgeId);
        if (knowledge == null) {
            return Result.fail();
        }
        //直接存储二进制数据，文件类型
        knowledge.setImageType(file.getContentType());
        knowledge.setImageBytes(file.getBytes());
        //更新用户数据
        return knowledgeService.updateById(knowledge) ? Result.suc() : Result.fail();
    }

    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String keywords = (String)param.get("keywords");
        
        Page<Knowledge> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Knowledge> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(keywords) && !"null".equals(keywords)){
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(Knowledge::getTitle, keywords)
                            .or()
                            .like(Knowledge::getPublisherNo, keywords)
            );
        }
        System.out.println("查询条件: " + lambdaQueryWrapper.getCustomSqlSegment());
        IPage result = knowledgeService.pageK(page,lambdaQueryWrapper);
        List<Knowledge> records = result.getRecords();
        return  Result.suc(records,result.getTotal());

    }
}
